﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using System.Collections;
using ILX.SharePoint.Util;
using ILX.SharePoint.Util.ResourceConst;
namespace SPUtility
{
   public class WorkflowHelper
    {
       SPUserToken curUserToken = null;
       public WorkflowHelper()
       { }
       public WorkflowHelper(string userLoginName)
       {
           try
           {
               if (string.IsNullOrEmpty(userLoginName))
               {
                   curUserToken = SPContext.Current.Web.CurrentUser.UserToken;
               }
               else
               {
                   curUserToken = SPContext.Current.Web.Users[userLoginName].UserToken;
               }
           }
           catch (Exception ex)
           {
           }
          
       }



       public  void ApproveWFTask(int itemid)
       {
           int wfItemID = default(int);
           Guid wfListID = Guid.Empty;
           string wfName = string.Empty;
           SPUserToken userToken = null;
           using (SPSite site = new SPSite("http://spdev"))
           {
               using (SPWeb objWeb = site.OpenWeb())
               {
                   //SPUserToken curUserToken  = SPContext.Current.Web.Users[""].UserToken;
                  // userToken = objWeb.Site.RootWeb.AllUsers["sp\\test1"].UserToken;
                   //objWeb.Users.g
                   SPList list = objWeb.Lists["TaskHandler"];
                   SPList listTasks = objWeb.Lists["ILXWFTask"];


                   SPListItem item = listTasks.GetItemById(itemid);
                   //wfItemID =
                   int.TryParse(string.Format("{0}", item["WorkflowItemId"]), out wfItemID);
                   wfName = item["WorkflowName"].ToString();
                   if (item["WorkflowListId"] != null)
                   {
                       wfListID = new Guid(string.Format("{0}", item["WorkflowListId"]));
                   }
               }
           }

           ApproveWFTask(wfItemID, wfListID, wfName, itemid, userToken,true);

       }

       public void ApproveRejectWFTask(int itemid, bool Approved)
       {
           string url = "http://spdev";
           string listTaskHandler="TaskHandler";
           string wfName = "mul";
           int wfItemID = default(int);
           Guid wfListID = Guid.Empty;
           SPUserToken userToken = null;
           using (SPSite site = new SPSite("http://spdev"))
           {
               using (SPWeb objWeb = site.OpenWeb())
               {
                   //SPUserToken curUserToken  = SPContext.Current.Web.Users[""].UserToken;
                   // userToken = objWeb.Site.RootWeb.AllUsers["sp\\test1"].UserToken;
                   //objWeb.Users.g
                   SPList list = objWeb.Lists["TaskHandler"];
                   SPList listTasks = objWeb.Lists["ILXWFTask"];


                   SPListItem item = listTasks.GetItemById(itemid);
                   //wfItemID =
                   int.TryParse(string.Format("{0}", item["WorkflowItemId"]), out wfItemID);
                   wfName = item["WorkflowName"].ToString();
                   if (item["WorkflowListId"] != null)
                   {
                       wfListID = new Guid(string.Format("{0}", item["WorkflowListId"]));
                   }
               }
           }


         //  if (Approved)
           {
               ApproveWFTask(wfItemID, wfListID, wfName, itemid, userToken, Approved);
           }
          // else
           {
             //  CancelWFTask(wfItemID, url, listTaskHandler, wfName);
           }
          

       }
       public  void ApproveWFTask(int wfItemID, Guid wfListID, string wfName, int taskID, SPUserToken curUserToken, bool Approve)
       {
           using (SPSite site = new SPSite("http://spdev"))
           {
               using (SPWeb objWeb = site.OpenWeb())
               {
                   objWeb.AllowUnsafeUpdates = true;
                   //SPUserToken curUserToken  = SPContext.Current.Web.Users[""].UserToken;

                   SPList list = objWeb.Lists[wfListID];

                   SPListItem item = list.GetItemById(wfItemID);

                   //SPWorkflowTemplate template = objWeb.WorkflowTemplates.GetTemplateByName("Approval", objWeb.Locale);

                   Console.WriteLine(item.Title);

                   SPWorkflowTaskCollection tskC = (from SPWorkflow spwfa in item.Workflows
                                                    where spwfa.AssociationId ==
                                                    (
                                                        (
                                                         from SPWorkflowAssociation associ in list.WorkflowAssociations
                                                         where associ.Name.Equals("mul", StringComparison.CurrentCultureIgnoreCase)
                                                         select associ.Id
                                                         )
                                                      .
                                                      FirstOrDefault()
                                                      )
                                                    select spwfa.Tasks
                              ).FirstOrDefault();


                   var de = from SPWorkflowTask sss in tskC
                            where string.Format("{0}",
                                sss["Status"]) != "Completed" && (sss.ID == taskID|| !Approve)
                            select sss;

                   foreach (var tsk in de)
                   {
                       Console.WriteLine(list.WorkflowAssociations[0].Id);
                       Console.WriteLine(tsk.Name);
                       Console.WriteLine(tsk.ID);
                       Console.WriteLine(tsk.Title);
                       // alter the task
                     //  tsk[SPBuiltInFieldId.TaskStatus] = "Rejected";
                       Hashtable ht = new Hashtable();
                       ht[SPBuiltInFieldId.Completed] = "TRUE";
                       ht[SPBuiltInFieldId.PercentComplete] = 1;
                       ht[SPBuiltInFieldId.TaskStatus] = Approve ? "Completed" : "Reject";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);
                       Console.WriteLine(SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true).ToString());
                       if (!Approve)
                       {
                           ///If rejected then system automatically cancel and removes all 
                           /// the associatem items therefore further task is not required
                           /// therefre it must stop after single reject.
                           /// Once item Rejected entire task will be rejected.
                           break;
                       }

                   }
                   Console.WriteLine("***********************************");
                   objWeb.AllowUnsafeUpdates = false;
                   objWeb.Update();
               }
           }
       }


       public void CancelWFTask(int wfItemID, string url, string listName, string wfName)
       {
           SPSecurity.RunWithElevatedPrivileges(delegate()
           {
               using (SPSite site = new SPSite(url))
               {
                   using (SPWeb web = site.OpenWeb())
                   {
                       SPWorkflowManager manager = site.WorkflowManager;
                       SPListItem item = web.Lists[listName].GetItemById(wfItemID);

                       foreach (SPWorkflow workflow in manager.GetItemActiveWorkflows(item))
                       {

                           foreach (SPWorkflowTask t in workflow.Tasks)
                           {
                               t["Status"] = "Canceled";
                               t.Update();

                           }

                           SPWorkflowManager.CancelWorkflow(workflow);

                           break;
                       }

                       


                   }
               }
           });
       }

       string taskapprovalRepository = "taskapprovalRepository";
       Dictionary<string, string> Dict = new Dictionary<string, string>();
       public bool RjectWFProcess(string siteUrl, string listName, string fieldName, string itemID, string workflowAssociationName, string currentApprovalLevel)
       {
           bool status = false;
           using (SPSite site = new SPSite(siteUrl))
           {
               using (SPWeb objWeb = site.OpenWeb())
               {
                   SPList list = objWeb.GetList(listName);
                   SPListItem item = null;// list.Items.GetItemById(itemID);
                   foreach (SPListItem item1 in list.Items)
                   {
                       if (item1[fieldName] != null && item1[fieldName].ToString() == itemID)
                       {
                           item = item1;
                           break;
                       }
                   }
                   if (item == null)
                   {
                       return false;
                   }
                   //SPWorkflowTemplate template =          objWeb.WorkflowTemplates.GetTemplateByName("Approval", objWeb.Locale);
                   Console.WriteLine(item.Title);
                   var tskC = (from SPWorkflow spwfa in item.Workflows
                               where spwfa.AssociationId ==
                               (
                                   (
                                    from SPWorkflowAssociation associ in list.WorkflowAssociations
                                    where associ.Name.Equals(workflowAssociationName, StringComparison.CurrentCultureIgnoreCase)
                                    select associ.Id
                                    )
                                 .
                                 FirstOrDefault()
                                 )
                               select spwfa.Tasks
                              ).FirstOrDefault();

                   foreach (SPWorkflowTask tsk in tskC)// item.Tasks)
                   {

                       Console.WriteLine(list.WorkflowAssociations[0].Id);
                       Console.WriteLine(tsk.Name);
                       Console.WriteLine(tsk.ID);
                       Console.WriteLine(tsk.Title);
                       // alter the task
                       Hashtable ht = new Hashtable();
                       ht[SPBuiltInFieldId.Completed] = "TRUE";
                       ht[SPBuiltInFieldId.PercentComplete] = 1;
                       ht[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);
                       ht["ApprovalStatus"] = "Reject";

                       Dict.Add("Title", tsk.Title);
                       Dict.Add("TaskOutCome", "Reject");
                       Dict.Add("ShortDescription", tsk.Title + "___>" + itemID);
                       Dict.Add("WFTaskInstanceConfigID", item.ID.ToString() );
                       Dict.Add("ApprovalLevel", currentApprovalLevel);
                       // Mark the entry as approved
                       status = SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true);
                       AddToLog(siteUrl, taskapprovalRepository);
                       break;
                   }

                   //objWeb.Update();
               }
           }

         
           return status;
       }

       private void AddToLog(string siteUrl, string listName)
       {
           //ListActivity lstActivity = new ListActivity();
         //  lstActivity.AddItem(siteUrl, listName, Dict);
       }


       public bool ApproveWFProcess(string siteUrl, string listName, string fieldName, string itemID, string workflowAssociationName, string currentApprovalLevel, Guid taskUniqueGuid)
       {
           bool status = false;
           SPSite site = null;
           if (curUserToken != null)
           {
               site = new SPSite(siteUrl,curUserToken);
           }
           else
           {
               site = new SPSite(siteUrl);
           }
           try
           {
               using (SPWeb objWeb = site.OpenWeb())
               {
                   SPList list = objWeb.GetList(listName);
                   SPListItem item = null;// list.Items.GetItemById(itemID);
                   foreach (SPListItem item1 in list.Items)
                   {
                       if (item1[fieldName] != null && item1[fieldName].ToString() == itemID)
                       {
                           item = item1;
                           break;
                       }
                   }
                   if (item == null)
                   {
                       return false;
                   }
                   //SPWorkflowTemplate template =          objWeb.WorkflowTemplates.GetTemplateByName("Approval", objWeb.Locale);
                   Console.WriteLine(item.Title);
                   var tskC = (from SPWorkflow spwfa in item.Workflows
                               where spwfa.AssociationId ==
                               (
                                   (
                                    from SPWorkflowAssociation associ in list.WorkflowAssociations
                                    where associ.Name.Equals(workflowAssociationName, StringComparison.CurrentCultureIgnoreCase)
                                    select associ.Id
                                    )
                                 .
                                 FirstOrDefault()
                                 )
                               select spwfa.Tasks
                              ).FirstOrDefault();

                   foreach (SPWorkflowTask tsk in tskC)// item.Tasks)
                   {

                       Console.WriteLine(list.WorkflowAssociations[0].Id);
                       Console.WriteLine(tsk.Name);
                       Console.WriteLine(tsk.ID);
                       Console.WriteLine(tsk.Title);
                       // alter the task
                       Hashtable ht = new Hashtable();
                       ht[SPBuiltInFieldId.Completed] = "TRUE";
                       ht[SPBuiltInFieldId.PercentComplete] = 1;
                       ht[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);
                       ht["ApprovalStatus"] = "Accept";
                       ht["TaskUniqueID"] = taskUniqueGuid;


                       Dict.Add("Title", tsk.Title);
                       Dict.Add("TaskOutCome", "Accept");
                       Dict.Add("ShortDescription", tsk.Title + "  {" + itemID + "}");
                       Dict.Add("WFTaskInstanceConfigID", item.ID.ToString());
                       Dict.Add("ApprovalLevel", currentApprovalLevel);

                       // Mark the entry as approved
                       status = SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true);
                       AddToLog(siteUrl, taskapprovalRepository);
                       try
                       {

                       }
                       catch (Exception)
                       {

                           throw;
                       }
                       break;
                   }

                   //objWeb.Update();
               }
           }
           catch (Exception ex)
           {


           }
           finally
           {
               site.Dispose();
           }
               
           
           return status;
       }


       public bool ApproveWFProcess(string siteUrl , string listName, int itemID, string workflowAssociationName, string currentApprovalLevel )
       {
           bool status = false;
           using (SPSite site = new SPSite(siteUrl))
           {
               using (SPWeb objWeb = site.OpenWeb())
               {
                   SPList list = objWeb.Lists[listName];
                   SPListItem item = list.Items.GetItemById(itemID);
                   //SPWorkflowTemplate template =          objWeb.WorkflowTemplates.GetTemplateByName("Approval", objWeb.Locale);
                   Console.WriteLine(item.Title);
                   var tskC = (from SPWorkflow spwfa in item.Workflows
                               where spwfa.AssociationId ==
                               (
                                   (
                                    from SPWorkflowAssociation associ in list.WorkflowAssociations
                                    where associ.Name.Equals(workflowAssociationName, StringComparison.CurrentCultureIgnoreCase)
                                    select associ.Id
                                    )
                                 .
                                 FirstOrDefault()
                                 )
                               select spwfa.Tasks
                              ).FirstOrDefault();
                  
                   foreach (SPWorkflowTask tsk in tskC)// item.Tasks)
                   {

                       Console.WriteLine(list.WorkflowAssociations[0].Id);
                       Console.WriteLine(tsk.Name);
                       Console.WriteLine(tsk.ID);
                       Console.WriteLine(tsk.Title);
                       // alter the task
                       Hashtable ht = new Hashtable();
                       ht[SPBuiltInFieldId.Completed] = "TRUE";
                       ht[SPBuiltInFieldId.PercentComplete] = 1;
                       ht[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);
                       ht["ApprovalStatus"] = "Accept";


                       Dict.Add("Title", tsk.Title);
                       Dict.Add("TaskOutCome", "Accept");
                       Dict.Add("ShortDescription", tsk.Title + "___>" + itemID);
                       Dict.Add("WFTaskInstanceConfigID", item.ID.ToString() );
                       Dict.Add("ApprovalLevel", currentApprovalLevel);
                       // Mark the entry as approved
                       status = SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true);
                       AddToLog(siteUrl, taskapprovalRepository);
                       break;
                   }

                   //objWeb.Update();
               }
           }
           return status;
       }

       public bool CancelWFProcess(string siteUrl, string listName, int itemID, string workflowAssociationName, string currentApprovalLevel)
       {
           using (SPSite site = new SPSite(siteUrl))
           {
               using (SPWeb objWeb = site.OpenWeb())
               {
                   SPList list = objWeb.Lists[listName];
                   SPListItem item = list.Items.GetItemById(itemID);
                   //SPWorkflowTemplate template =          objWeb.WorkflowTemplates.GetTemplateByName("Approval", objWeb.Locale);
                   Console.WriteLine(item.Title);
                   var tskC = (from SPWorkflow spwfa in item.Workflows
                               where spwfa.AssociationId ==
                               (
                                   (
                                    from SPWorkflowAssociation associ in list.WorkflowAssociations
                                    where associ.Name.Equals(workflowAssociationName, StringComparison.CurrentCultureIgnoreCase)
                                    select associ.Id
                                    )
                                 .
                                 FirstOrDefault()
                                 )
                               select spwfa
                              ).FirstOrDefault();


                   if (tskC != null)
                   {

                       Dict.Add("Title", item.Title);
                       Dict.Add("TaskOutCome", "Cancelled");
                       Dict.Add("ShortDescription", item.Title + "___>" + itemID);
                       Dict.Add("WFTaskInstanceConfigID", item.ID.ToString());
                       Dict.Add("ApprovalLevel", currentApprovalLevel);

                       SPWorkflowManager.CancelWorkflow(tskC);
                       AddToLog(siteUrl, taskapprovalRepository);
                       return true;
                   }
               }
           }
           return false;
       }


       private DateTime ActualDate(DateTime curDate, int Days, SPList holidayList)
       {
           int k = 1;
           double actualDays = 1;
           string weekend1 = "sunday";
           string weekend2 = "saturday";
           while (k <= Days)
           {
               if (
                   !curDate.AddDays(actualDays).DayOfWeek.ToString().Equals(weekend1, StringComparison.CurrentCultureIgnoreCase)
                   &&
                   !curDate.AddDays(actualDays).DayOfWeek.ToString().Equals(weekend2, StringComparison.CurrentCultureIgnoreCase)
                   )
               {
                   var dat = (from SPListItem itm in holidayList.Items
                              where itm["HolidayDate"] != null &&
                             String.Format("{0:d}", (DateTime)itm["HolidayDate"]) == String.Format("{0:d}", curDate.AddDays(actualDays))
                              select itm).FirstOrDefault();
                   if (dat == null)
                   {

                       k++;
                   }
               }

               actualDays++;
               // k++;

           }
           if (Days == 0)
           {


               var dat1 = (from SPListItem itm in holidayList.Items
                           where itm["HolidayDate"] != null &&
                          String.Format("{0:d}", (DateTime)itm["HolidayDate"]) == String.Format("{0:d}", curDate)
                           select itm).FirstOrDefault();
               if (dat1 != null)
               {
                   // curDate = curDate.AddDays(1);
                   return ActualDate(curDate.AddDays(1), 1, holidayList);
               }
           }
           else
           {
               actualDays = (k > 0 ? actualDays - 1 : actualDays);
           }
           if (
                   curDate.AddDays(actualDays).DayOfWeek.ToString().Equals(weekend1, StringComparison.CurrentCultureIgnoreCase)
                   ||
                   curDate.AddDays(actualDays).DayOfWeek.ToString().Equals(weekend2, StringComparison.CurrentCultureIgnoreCase)
                   )
           {


               return ActualDate(curDate.AddDays(actualDays + 1), 0, holidayList);
               //actualDays++;
           }


           return curDate.AddDays(actualDays);
       }
       public void ProcessBatchInsert(string siteUrl, string activityMasterConfigList, string workflowName, string taskFields, int WFItemID, string SourceListTitle, string ListUrl)
       {
           //double aa = ActualDays(5);

           double hourDiff = (24 - (System.DateTime.Now.Minute + 1) / 60D);
           hourDiff = Math.Round(hourDiff, 2) - System.DateTime.Now.Hour;
           // return;
           // string listGuid = "C7F6A36F-BD2E-484A-A18C-05D9F69AC554";
           StringBuilder query = new StringBuilder();

           using (SPSite site = new SPSite(siteUrl))
           {

               using (SPWeb objWeb = site.OpenWeb())
               {
                   SPList configList = objWeb.Lists["Task Activity Master"];
                   SPList holidayList = objWeb.Lists["Holiday"];
                   SPList configCustomList = objWeb.Lists["ApprovalLevelCustom"];
                   StringBuilder sbHoliday = new StringBuilder();

                   var listItem = (from SPListItem itm in configList.Items
                                   where
                                   itm["TaskActivity"] != null
                                   &&
                                   itm["TaskActivity"].ToString().Contains(workflowName)
                                   orderby itm["ApprovalLevel"] ascending
                                   select itm );


                   var listItemCustom = configCustomList.GetItems(
                       new SPQuery()
                       {
                           Query = string.Format(PortalQuery.CustomTaskActivityQuery, SourceListTitle, WFItemID, workflowName)
                       }

                       );

                   if (listItemCustom != null)
                   {
                       while (listItemCustom.Count > 0)
                       {
                           listItemCustom.Delete(0);
                       }
                   }

                    

                   StringBuilder query1 = new StringBuilder();
                   DateTime curDate = System.DateTime.Now;
                   foreach (var item in listItem)
                   {
                       query.AppendFormat(
                      "<Method ID=\"{0}\">" +
                      "<SetList>{1}</SetList>" +
                      "<SetVar Name=\"ID\">New</SetVar>" +
                      "<SetVar Name=\"Cmd\">Save</SetVar>", item.ID, configCustomList.ID.ToString("d"));
                      
                       query.AppendFormat("<SetVar Name=\"{1}\">{0}</SetVar>", WFItemID, "urn:schemas-microsoft-com:office:office#WFItemID");
                       query.AppendFormat("<SetVar Name=\"{1}\">{0}</SetVar>", SourceListTitle, "urn:schemas-microsoft-com:office:office#SourceListTitle");
                       query.AppendFormat("<SetVar Name=\"{1}\">{0}</SetVar>", ListUrl, "urn:schemas-microsoft-com:office:office#ListUrl");

                       foreach (string fld in taskFields.Replace("\r", "").Replace("\n", "").Split(','))
                       {
                           var curfld = fld.Trim();
                           if (curfld.Contains("DueDate"))
                           {
                               curDate = ActualDate(curDate, int.Parse(item["Due Days".Replace(" ", "")].ToString()), holidayList);
                               query.AppendFormat("<SetVar Name=\"{1}\">{0}</SetVar>",
                                    Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(
                                   curDate.AddHours(
                                    hourDiff)),
                                    "urn:schemas-microsoft-com:office:office#" + curfld.Replace(" ", ""));
                           }
                           else
                               query.AppendFormat("<SetVar Name=\"{1}\">{0}</SetVar>", item[curfld.Replace(" ", "")], "urn:schemas-microsoft-com:office:office#" + curfld.Replace(" ", ""));
                       }
                       query.AppendFormat("</Method>");
                   }

                   string output = objWeb.ProcessBatchData(string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                          "<ows:Batch OnError=\"Return\">{0}</ows:Batch>", query.ToString()));
                   Console.WriteLine(output);
               }
           }
       }

       public  void AutoCompleteApproval(int itemid)
       {
           using (SPSite site = new SPSite("http://spdev"))
           {
               using (SPWeb objWeb = site.OpenWeb())
               {
                   SPList list = objWeb.Lists["TaskHandler"];
                   SPList listTasks = objWeb.Lists["ILXWFTask"];


                   SPListItem item = list.GetItemById(itemid);
                   //SPWorkflowTemplate template =          objWeb.WorkflowTemplates.GetTemplateByName("Approval", objWeb.Locale);
                   Console.WriteLine(item.Title);
                   SPWorkflowTaskCollection tskC = (from SPWorkflow spwfa in item.Workflows
                                                    where spwfa.AssociationId ==
                                                    (
                                                        (
                                                         from SPWorkflowAssociation associ in list.WorkflowAssociations
                                                         where associ.Name.Equals("mul", StringComparison.CurrentCultureIgnoreCase)
                                                         select associ.Id
                                                         )
                                                      .
                                                      FirstOrDefault()
                                                      )
                                                    select spwfa.Tasks
                              ).FirstOrDefault()

                              ;


                   var de = from SPWorkflowTask sss in tskC where string.Format("{0}", sss["Status"]) != "Completed" select sss;
                   foreach (var tsk in de)
                   {
                       //if (string.Format("{0}", tsk["Status"]) != "Completed")
                       {
                           Console.WriteLine(list.WorkflowAssociations[0].Id);
                           Console.WriteLine(tsk.Name);
                           Console.WriteLine(tsk.ID);
                           Console.WriteLine(tsk.Title);
                           // alter the task
                           Hashtable ht = new Hashtable();
                           ht[SPBuiltInFieldId.Completed] = "TRUE";
                           ht[SPBuiltInFieldId.PercentComplete] = 1;
                           ht[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);

                           // Mark the entry as approved
                           Console.WriteLine(SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true).ToString());
                       }
                   }
                   foreach (SPWorkflowTask tsk in tskC)// item.Tasks)
                   {
                       if (string.Format("{0}", tsk["Status"]) != "Completed")
                       {
                           Console.WriteLine(list.WorkflowAssociations[0].Id);
                           Console.WriteLine(tsk.Name);
                           Console.WriteLine(tsk.ID);
                           Console.WriteLine(tsk.Title);
                           // alter the task
                           Hashtable ht = new Hashtable();
                           ht[SPBuiltInFieldId.Completed] = "TRUE";
                           ht[SPBuiltInFieldId.PercentComplete] = 1;
                           ht[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);

                           // Mark the entry as approved
                           //  Console.WriteLine(SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true).ToString());
                       }
                   }

                   objWeb.Update();
               }
           }
       }

       private void Approveask(int itemid, int taskID)
       {
           using (SPSite site = new SPSite("http://spdev"))
           {
               using (SPWeb objWeb = site.OpenWeb())
               {
                   //SPUserToken curUserToken  = SPContext.Current.Web.Users[""].UserToken;
                   using (SPSite site1 = new SPSite("http://spdev"))
                   {
                       using (SPWeb objWeb1 = site1.OpenWeb())
                       {
                       }
                   }

                   SPList list = objWeb.Lists["TaskHandler"];
                   SPList listTasks = objWeb.Lists["ILXWFTask"];


                   SPListItem item = list.GetItemById(itemid);
                   //SPWorkflowTemplate template =          objWeb.WorkflowTemplates.GetTemplateByName("Approval", objWeb.Locale);
                   Console.WriteLine(item.Title);
                   SPWorkflowTaskCollection tskC = (from SPWorkflow spwfa in item.Workflows
                                                    where spwfa.AssociationId ==
                                                    (
                                                        (
                                                         from SPWorkflowAssociation associ in list.WorkflowAssociations
                                                      //  -- where associ.Name.Equals("mul", StringComparison.CurrentCultureIgnoreCase)
                                                         select associ.Id
                                                         )
                                                      .
                                                      FirstOrDefault()
                                                      )
                                                    select spwfa.Tasks
                              ).FirstOrDefault()

                              ;


                   var de = from SPWorkflowTask sss in tskC
                            where
                            string.Format("{0}", sss["Status"]) != "Completed"
                            && sss.ID == taskID
                            select sss;
                   foreach (var tsk in de)
                   {
                       //if (string.Format("{0}", tsk["Status"]) != "Completed")
                       {
                           Console.WriteLine(list.WorkflowAssociations[0].Id);
                           Console.WriteLine(tsk.Name);
                           Console.WriteLine(tsk.ID);
                           Console.WriteLine(tsk.Title);
                           // alter the task
                           Hashtable ht = new Hashtable();
                           ht[SPBuiltInFieldId.Completed] = "TRUE";
                           ht[SPBuiltInFieldId.PercentComplete] = 1;
                           ht[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);

                           // Mark the entry as approved
                            Console.WriteLine(SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true).ToString());
                       }
                   }
                   Console.WriteLine("***********************************");
                   objWeb.Update();
               }
           }
       }


   
   }
}
